<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userApi } from '../api/user'

const router = useRouter()

const formRef = ref(null)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const loading = ref(false)

const handleLogin = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    const res = await userApi.login(loginForm)
    
    if (res.token && res.user) {
      // 先清除旧的数据
      localStorage.clear()
      
      // 保存登录信息
      localStorage.setItem('token', JSON.stringify(res.token))
      localStorage.setItem('user', JSON.stringify(res.user))
      
      // 显示登录成功消息
      ElMessage.success('登录成功')
      
      // 根据用户角色跳转
      const targetPath = res.user.is_admin || res.user.is_superuser ? '/backend/dashboard' : '/frontend'
      router.replace(targetPath)
    } else {
      ElMessage.error('登录失败：用户信息或token无效')
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h2>猫眼电影数据分析系统</h2>
      <el-form 
        ref="formRef"
        :model="loginForm" 
        :rules="rules"
        label-width="0"
      >
        <el-form-item>
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <div class="register-link">
          还没有账号？
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #1f1f1f 0%, #3c3c3c 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-box {
  width: 90%;
  max-width: 400px;
  padding: clamp(20px, 5vw, 40px);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
}

h2 {
  color: #fff;
  text-align: center;
  margin-bottom: clamp(20px, 5vw, 30px);
  font-size: clamp(1.5rem, 4vw, 2rem);
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: clamp(15px, 4vw, 20px);
  color: #fff;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-input__inner) {
  color: #fff !important;
}

:deep(.el-input__prefix-icon) {
  color: #fff !important;
}
</style> 